package config

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
	"time"
)

type Config struct {
	Server   ServerConfig
	Database DatabaseConfig
	JWT      JWTConfig
}

type ServerConfig struct {
	Port         string
	Mode         string
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

type DatabaseConfig struct {
	Host               string `json:"host" yaml:"host"`
	Port               int    `json:"port" yaml:"port"`
	User               string `json:"user" yaml:"user"`
	Password           string `json:"password" yaml:"password"`
	Name               string `json:"name" yaml:"name"`
	MaxIdleConnections int
	MaxOpenConnections int
	LogLevel           string
}

func (conf *Config) GetDatabaseDSN() string {
	return conf.Database.User + ":" + conf.Database.Password + "@tcp(" + conf.Database.Host + ":" + fmt.Sprintf("%d", conf.Database.Port) + ")/" + conf.Database.Name + "?charset=utf8mb4&parseTime=True&loc=Local"
}

type JWTConfig struct {
	Secret  string
	Expires int
	Issuer  string
}

func InitConfig() (*Config, error) {
	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %s", err)
	}

	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		log.Fatalf("从结构体中加载配置失败: %v", err)
		return nil, err
	}
	return &config, nil
}
